package com.winmastergames.remotemonitor;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;


public class MonitorStatus {
  public static final int NA = -1;
  public static final int SUNNY = 0;
  public static final int OVERCAST = 1;
  public static final int RAIN = 2;

  public String address = null;
  public String servicesOk = null;
  public String servicesFail = null;
  public int statusImg = NA;

  public MonitorStatus( String address, String servicesOk, String servicesFail, int statusImg ) {
	if(servicesOk == "-1" && servicesFail == "-1")
	{
    	this.servicesOk = "?";
    	this.servicesFail = "?";	
	} else {
    	this.servicesOk = servicesOk;
    	this.servicesFail = servicesFail;
	}
	this.statusImg = statusImg;
	this.address = address;
  }
  
  public void checkServices() {
	  //Setup some Variables
	  int c_servicesOk = 0;
	  int c_servicesFailed = 0;
	  //Check the Services
	  if(checkService(address, 80) == true)
	  {
		  c_servicesOk += 1;
	  } else {
		  c_servicesFailed += 1;
	  }
	  //Set the Variables to Display
	  this.servicesOk = String.valueOf(c_servicesOk);
	  this.servicesFail = String.valueOf(c_servicesFailed);
	  if(c_servicesFailed > 0)
	  {
		  this.statusImg = RAIN;
	  } else {
		  this.statusImg = SUNNY;
	  }
  }
  
  public boolean checkService(String address, int port)
  {
	  Socket s = new Socket();
	  try {
		s.bind(null);
	} catch (IOException e1) {}
	  try {
		s.connect(new InetSocketAddress(address, port), 500);
		return true;
	} catch (IOException e) {
		return false;
	}
  }

  public String getAddress() {
	return address;
  }

  public String getServicesOk() {
	return servicesOk;
  }
  
  public String getServicesFail() {
	  return servicesFail;
  }

  public int getResource() {
	switch( statusImg ) {
	  case SUNNY:
			return R.drawable.weather_sunny;

	  case OVERCAST:
			return R.drawable.weather_overcast;

	  case RAIN:
			return R.drawable.weather_rain;
	}
	return R.drawable.weather_rain;
  }
}
